import { getToken } from '@/utils/cookie'
import { createRouter, createWebHistory } from 'vue-router'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: "/",
      redirect: "/oj/login",
    },
    {
      path: "/oj/login",
      name: "Login",
      component: () => import("../views/Login.vue")
    },
    {
      path: "/oj/system",
      name: "System",
      component: () => import("../views/System.vue")
    },
    {
      path: "/oj/layout",
      name: "Layout",
      component: () => import("../views/Layout.vue"),
      children: [
        {
          path: "cuser",
          name: "Cuser",
          component: () => import("../views/Cuser.vue")
        },
        {
          path: "exam",
          name: "Exam",
          component: () => import("../views/Exam.vue")
        },
        {
          path: "question",
          name: "Question",
          component: () => import("../views/Question.vue")
        },
        {
          path: "updateExam",
          name: "UpdateExam",
          component: () => import("../views/UpdateExam.vue")
        }
      ]
    }

  ]
})

// 在router进行路由之前，如果用户未登录而跳到了其他的界面，那么就需要跳转到登录页面提示用户登录
// 如果用户已经登陆过，也就是说存储的cookie没有过期的话
router.beforeEach((to,from,next) => {
  if (getToken()) {
    if (to.path == '/oj/login') {
      next({path : '/oj/layout'});
    }else {
      next();
    }
  } else {
    if (to.path != '/oj/login') {
      next({path : '/oj/login'});
    }else {
      next()
    }
  }
})

export default router
